package primalgorithms.list;

public class _04MergeTwoLists {
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null){
            return list2;
        }else if(list2 == null){
            return list1;
        }
        ListNode p1 = list1, p2 = list2;
        ListNode res = new ListNode();
        ListNode head = res;
        while (p1 != null && p2 != null){
            if(p1.val < p2.val){
                res.val = p1.val;
                p1 = p1.next;
                res.next = new ListNode();
                res = res.next;
            }else {
                res.val = p2.val;
                p2 = p2.next;
                res.next = new ListNode();
                res = res.next;
            }
        }
        //执行到此处说明p1和p2至少有一个指向null
        //注意：这里不可以写res = p1和res = p2
        //因为此时head的尾结点是res的内存地址，直接将res赋值的话并不会影响到head链表中的尾结点！！！
        if(p1 != null){
            res.val = p1.val;
            res.next = p1.next;
        }else {
            res.val = p2.val;
            res.next = p2.next;
        }
        return head;
    }
}
